package org.hnxxxy.ebms.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import org.hnxxxy.ebms.pojo.RecruitStu;
import org.hnxxxy.ebms.pojo.Role;
import org.hnxxxy.ebms.pojo.Student;
import org.hnxxxy.ebms.service.StudentService;
import org.hnxxxy.ebms.util.CommonUntil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description:
 * @Author WANGWEI
 * @Date: 2021/5/15  22:24
 * @EMAIL: 1377366738@qq.com
 */
public class EasyExcelListener extends AnalysisEventListener<Student> {

    private static final Logger LOGGER = LoggerFactory.getLogger(EasyExcelListener.class);

    private static final int BATCH_COUNT = 50;
    List<Student> list = new ArrayList<Student>();

    private StudentService studentService;

    public EasyExcelListener(StudentService studentService){
        this.studentService = studentService;
    }

    @Override
    public void invoke(Student student, AnalysisContext analysisContext) {
        LOGGER.info("解析到一条数据:{}", student);
        Role role = studentService.getRole(CommonUntil.getId());
        student.setRecruitStuId(role.getUserId());
        list.add(student);
        if (list.size() >= BATCH_COUNT){
            saveData();
            list.clear();
        }
    }

    private void saveData() {
        LOGGER.info("{}条数据，开始存储数据库！", list.size());
        studentService.saveBatch(list);
        LOGGER.info("存储数据库成功！");
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
        LOGGER.info("所有数据解析完成！");
    }
}
